package RabbitMQ.rpc;
import RabbitMQ.Constants.Constants;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.*;
public class RpcClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//        1.建立连接
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection=connectionFactory.newConnection();
//        2.开启信道
        Channel channel=connection.createChannel();
//        这里使用默认的交换机,不再进行声明
//        声明队列
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE,true,false,false,null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE,true,false,false,null);
//        发送请求
        String msg="hello,rpc";
//        设置唯一的标识符
        String correlationID= UUID.randomUUID().toString();
//        设置请求的相关属性
        AMQP.BasicProperties props=new AMQP.BasicProperties().builder()
                .correlationId(correlationID)
                .replyTo(Constants.RPC_RESPONSE_QUEUE)
                .build();
//        发送消息
        channel.basicPublish("",Constants.RPC_REQUEST_QUEUE,props,msg.getBytes(StandardCharsets.UTF_8));
//        接收响应,这里使用阻塞队列来存储响应的信息.
        final BlockingQueue<String> response=new ArrayBlockingQueue<>(1);
//        对接收到的信息进行处理
        DefaultConsumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                 String respMsg=new String(body);
                System.out.println("接收到的消息是:"+respMsg);
//                如果correlationId保持一致,存入队列
                if(correlationID.equals(properties.getCorrelationId())){
//                    加入队列即可
                    response.offer(respMsg);
                }
            }
        };
        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE,true,consumer);
        String result=response.take();
        System.out.println("[RPC Client 响应结果]: "+result);
        channel.close();
        connection.close();
    }
}
